/* eslint-disable @typescript-eslint/ban-ts-comment */
import { Image, Popup, Toast } from '@nutui/nutui-react';
import { useRequest } from 'ahooks';
import { find, get } from 'lodash-es';
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import { apiBrowseByPost } from '@/application/apis/browseInfo';
import { apiGoodsHasStockByGet } from '@/application/apis/goods';
import { apiSignInByPost, apiSignInQueryByGet } from '@/application/apis/signIn';
import {
  apiTaskListByGet,
  apiTaskLotteryCardByGet,
  apiTaskQueryByGet,
  apiTaskReceiveCardByGet
} from '@/application/apis/task';
import { apiTaskSignupByPost, apiTaskSignupQueryByGet } from '@/application/apis/taskSignupInfo';
import { apiWinReceiveTaskByPost } from '@/application/apis/win';
import { ROUTE_MAP } from '@/application/constants/routerMap';
import { useGlobal } from '@/application/context/global';
import { useUser } from '@/application/hooks/use-user';
import { classNames as classnames } from '@/application/utils';
import { share } from '@/application/utils/share';
import Storage from '@/application/utils/storage';
import { Cards, Task } from '@/types/apiType';
import { TaskType } from '@/types/common';

import { useHome } from '../context';
import { CardDialog, PuzzlePieceContent } from './CardDialog';
import { SignSuccess } from './SignSuccess';

// const widthLink = {
//   2: {
//     url: '/pages/couponsPage/couponsPage',
//     appId: '20210011',
//     target: 1
//   },
//   3: {
//     url: 'https://at.ahlife.com/xiaosu-game/index.html',
//     appId: '',
//     target: 2
//   },
//   4: {
//     url: 'pages/packageD/liveLinkPage/index?eventId=7836226',
//     appId: 'gh_83d6248ff6f9',
//     target: 6
//   },
//   4: [
//     {
//       url: 'pages/packageD/urlLinkH5/index?url=https%3A%2F%2Fsuzhouhd.urthink.com%2Fa%2F82%2FxZ4G7Qml%2Findex',
//       appId: 'gh_83d6248ff6f9',
//       target: 6
//     },
//     {
//       url: 'pages/packageD/liveLinkPage/index?eventId=7836226',
//       appId: 'gh_83d6248ff6f9',
//       target: 6
//     }
//   ]
// };

const Button = ({
  text,
  classNames,
  onClick
}: {
  text: string;
  classNames?: string;
  onClick: VoidFunction;
}) => {
  return (
    <div
      onClick={onClick}
      className={classnames(
        'flex h-8 w-19 items-center justify-center rounded-full bg-[#FE4F05] text-sm font-medium text-white',
        classNames
      )}
    >
      {text}
    </div>
  );
};
const TaskButton = (props: {
  taskStatus: any;
  item: any;
  signInfo: any;
  needSignUp: any;
  goodStock: any;
  onClick: (item: any, type: string) => void;
}) => {
  const { item, taskStatus, signInfo, needSignUp, onClick, goodStock } = props;
  const curStatuse = get(taskStatus, `${item.id}.taskStatus`);
  // const curGoodStock = get(goodStock, `${item.id}`);

  // if (curGoodStock === false) return <div className="text-sm text-[#999]">奖励无库存</div>;
  switch (curStatuse) {
    case 'Y':
      return (
        <div className="text-sm text-[#999]" onClick={() => onClick(item, 'end')}>
          已完成
        </div>
      );
    case 'C':
      return <Button text="领取奖励" onClick={() => onClick(item, 'receiveRward')} />;
    case 'F':
      return <Button text={'领取碎片'} onClick={() => onClick(item, 'receiveCard')} />;
    case 'L':
      if (item.leftLotteryTimes > 0) {
        return <Button text={`领取碎片`} onClick={() => onClick(item, 'lottery')} />;
      }
      return (
        <Button
          text={item.taskType === TaskType.BROWSING_TASK ? '浏览' : '去完成'}
          classNames="bg-[#FF8A10] "
          onClick={() => onClick(item, 'normal')}
        />
      );
    default:
      if (item.taskType === 10) {
        if (signInfo?.signedToday) {
          return <div className="text-sm text-[#999]">今日已签到</div>;
        }
        return <Button text={'签到'} onClick={() => onClick(item, 'normal')} />;
      } else if (item.needSignUp && !needSignUp[item.id]) {
        return (
          <Button
            text="去报名"
            classNames="bg-[#FF8A10] "
            onClick={() => onClick(item, 'signUp')}
          />
        );
      }
      return (
        <Button
          text={item.taskType === TaskType.BROWSING_TASK ? '浏览' : '去完成'}
          classNames="bg-[#FF8A10] "
          onClick={() => onClick(item, 'normal')}
        />
      );
  }
};
export default function TaskList() {
  const { showTask, setShowTask, cardList, refreshData, reachCardInfo } = useHome();
  const navigate = useNavigate();
  const { goodInfo, activityInfo } = useGlobal();
  const { user } = useUser();
  const [taskStatus, setTaskStatus] = useState<AnyObject>({});
  const [goodStock, setGoodStock] = useState<AnyObject>({});
  const [taskList, setTaskList] = useState<any[]>([]);
  const [signInfo, setSignInfo] = useState<any>({});
  const [needSignUp, setNeedSignUp] = useState<any>({});

  const { run: loadTaskList } = useRequest(
    () =>
      apiTaskListByGet({ goodsId: goodInfo?.id as number, activityId: activityInfo?.id as number }),
    {
      manual: true,
      onSuccess: (result) => {
        result?.forEach((item) => {
          getTaskStatus(item);
          // getTaskGoodStock(item);
          if (item.needSignUp) getNeedSignUp(item);
        });
        const task = result || [];
        setTaskList(task);
      }
    }
  );

  //获取任务状态
  const getTaskStatus = async (item: Task) => {
    if (!user?.m1Status) return;
    return apiTaskQueryByGet(
      {
        taskId: item.id as number,
        goodsId: goodInfo?.id as number,
        activityId: activityInfo?.id as number
      },
      { hideLoading: true, hideToast: true }
    ).then((res) => setTaskStatus((prev) => ({ ...prev, [item.id as number]: res })));
  };

  // 获取奖励库存状态
  const getTaskGoodStock = async (item: Task) => {
    if (!user?.m1Status || !item.winGoodsId) return;
    return apiGoodsHasStockByGet({
      goodsId: item?.winGoodsId as number,
      activityId: activityInfo?.id as number
    }).then((res) => setGoodStock((prev) => ({ ...prev, [item.id as number]: res })));
  };
  // 获取任务是否需要报名
  const getNeedSignUp = async (item: Task) => {
    apiTaskSignupQueryByGet({
      taskId: item.id as number,
      goodsId: goodInfo?.id as number,
      activityId: activityInfo?.id as number
    }).then((res) =>
      setNeedSignUp((prev: any) => ({ ...prev, [item.id as number]: res?.signuped }))
    );
  };
  // 获取任务签名信息
  const getSignInfo = async () => {
    return apiSignInQueryByGet({ activityId: activityInfo?.id as number }).then((res: any) => {
      setSignInfo(res);
    });
  };
  useEffect(() => {
    if (user?.m1Status && goodInfo?.id) {
      getSignInfo().finally(loadTaskList);
      refreshData();
    }
  }, [user, goodInfo]);

  const handleNormal = async (item: any) => {
    const firstSign = find(taskList, { taskType: TaskType.FIRST_CHECK_IN_TASK });
    const continuedSign = find(taskList, { taskType: TaskType.ACCUMULATIVE_CHECK_IN_TASK });
    switch (item.taskType) {
      case TaskType.REFERRAL_TASK:
        loading.current = false;
        return share({
          content: '帮我集拼图，一起赢好礼',
          title: `快来帮我领取${goodInfo?.goodsName}`,
          url: `${window.location.origin}/invitee/${user?.userId}`
        });
      case TaskType.FIRST_CHECK_IN_TASK:
      case TaskType.ACCUMULATIVE_CHECK_IN_TASK:
        try {
          await apiSignInByPost();
          Toast.show({ title: '签到成功', lockScroll: true });
          getTaskStatus(firstSign);
          getTaskStatus(continuedSign);
          getSignInfo();
          refreshData();
        } catch (e) {
          console.error(e);
        } finally {
          loading.current = false;
        }
        break;
      case TaskType.BROWSING_TASK:
        loading.current = false;
        // eslint-disable-next-line no-case-declarations
        const browseUrls = JSON.parse(item.browseUrls || '');
        if (browseUrls.length > 0) {
          apiBrowseByPost({
            activityId: activityInfo?.id as number,
            goodsId: goodInfo?.id as number,
            taskId: item.id
          }).finally(() => {
            $Fw.navigateToCellSkip({
              ...browseUrls[item.finishedCount || 0]
            });
            window.location.reload();
          });
        }

        break;
      default: {
        if (item.browseUrls) {
          $Fw.navigateToCellSkip({
            ...item.browseUrls[0]
          });
        }
        loading.current = false;
      }
    }
  };

  const loading = useRef(false);
  const handleClick = async (item: Task, type: string) => {
    if (loading.current) return;
    const curItemStatus = get(taskStatus, `${item.id}`);
    loading.current = true;
    switch (type) {
      //需要报名
      case 'signUp':
        try {
          await apiTaskSignupByPost({
            activityId: activityInfo?.id,
            goodsId: goodInfo?.id,
            taskId: item.id
          });

          return SignSuccess.show({
            title: '报名成功',
            icon: '/images/home/sign_success.png',
            text: `完成${item.taskName},获得碎片~`,
            onConfirm: () => {
              getTaskStatus(item);
              getNeedSignUp(item);
              getSignInfo();
              refreshData();
            }
          });
        } catch (e) {
          console.log(e);
        } finally {
          loading.current = false;
        }
        break;
      case 'receiveRward':
        try {
          await apiWinReceiveTaskByPost({ userTaskId: curItemStatus.userTaskId as number });
          loading.current = false;
          if (item.taskType === TaskType.REFERRAL_TASK) {
            getTaskStatus(item).then(() => {
              handleClick(item, 'lottery');
            });
          } else {
            refreshData();
            return navigate(ROUTE_MAP.AWARD_LIST);
          }
        } catch (e) {
          console.log('领取奖励失败，', e);
        } finally {
          loading.current = false;
        }
        break;
      case 'lottery':
      case 'receiveCard':
        // eslint-disable-next-line no-case-declarations
        let result: unknown = {};
        if (
          curItemStatus?.leftLotteryTimes &&
          curItemStatus.leftLotteryTimes > 0 &&
          type === 'lottery'
        ) {
          result = await apiTaskLotteryCardByGet({
            taskId: item.id as number,
            activityId: activityInfo?.id as number,
            goodsId: goodInfo?.id as number
          });
        } else {
          result = await apiTaskReceiveCardByGet({
            activityId: activityInfo?.id as number,
            goodsId: goodInfo?.id as number,
            taskId: item.id as number
          });
        }
        // eslint-disable-next-line no-case-declarations
        const curCard = (get(result, `winCards`) || '').split(',').pop();
        // eslint-disable-next-line no-case-declarations
        const card = find(cardList, { id: Number(curCard) });

        return CardDialog.show({
          onConfirm: () => {
            getTaskStatus(item);
            getSignInfo();
            refreshData();
            loading.current = false;
          },
          children: (
            <PuzzlePieceContent
              taskId={item.id as number}
              cardsNum={cardList?.length || 6}
              hasPiece={reachCardInfo?.uniqWin?.length || 0}
              card={card as Cards}
              winCards={get(result, `winCards`) || ''}
              extra={{ ...item, ...(get(taskStatus, `${item.id}`) || {}) }}
            />
          )
        });
      case 'end':
        return;
      default:
        if (item.taskType === TaskType.ACCUMULATIVE_CHECK_IN_TASK && signInfo?.signedToday) {
          Toast.show({ title: '今日已签到', lockScroll: true });
          return;
        }
        handleNormal(item);
    }
  };

  const getTaskDesc = (item: Task) => {
    const curCard = get(taskStatus, `${item.id}`);
    let r = (item.taskDesc || '').replace('FIN_', curCard?.finishedCount || 0);
    r = r.replace(/TOTAL_/g, `${item.requirementCount}` || '0');
    r = r.replace(
      '碎片',
      `<Image src='/images/task/card.png' class="mx-1 inline-block !h-[13px] !w-4" />`
    );
    return r;
  };
  useEffect(() => {
    if (showTask) {
      document.body.classList.add('disable-page-scroll-task');
    } else {
      document.body.classList.remove('disable-page-scroll-task');
    }
  }, [showTask]);
  return (
    <Popup position="bottom" visible={showTask} round lockScroll onClose={() => setShowTask(false)}>
      <div className="pb-5">
        <div className="flex h-12.5 items-center justify-between bg-[#F1F7DE] px-3.75">
          <div className="text-[17px] font-medium text-[#333]">做任务 集碎片</div>
          <Image
            src={new URL('/images/task/btn_rw_close.png', import.meta.env.VITE_IMG_BASE_URL).href}
            className="relative -top-2 h-10 w-8.25"
            onClick={() => setShowTask(false)}
          />
        </div>
        <div className="max-h-[500px] overflow-auto">
          {taskList &&
            taskList?.length > 0 &&
            taskList.map((item, index) => {
              const curItemStatus = get(taskStatus, `${item.id}`);
              return (
                <div
                  key={item.id}
                  className={classnames(
                    'after:border-[rgba(198, 198, 198, .3)] relative flex h-24 items-center justify-between p-3.75 after:absolute after:bottom-0 after:left-3.75 after:right-0 after:border-b',
                    { 'after:hidden': index === taskList?.length - 1 }
                  )}
                >
                  <Image src={item?.icon} className="mr-2.5 h-13.75 w-13.75" />
                  <div className="flex h-full flex-1 flex-col justify-between">
                    <div className="font-medium">{item.taskName}</div>
                    <div
                      className="inline-block items-center text-xs text-[#999]"
                      dangerouslySetInnerHTML={{ __html: getTaskDesc(item) }}
                    ></div>
                    <div className="text-xs text-[#DE9D5A]">{item?.rewardDesc || ''}</div>
                  </div>

                  <TaskButton
                    onClick={handleClick}
                    item={{ ...curItemStatus, ...item }}
                    signInfo={signInfo}
                    taskStatus={taskStatus}
                    needSignUp={needSignUp}
                    goodStock={goodStock}
                  />
                </div>
              );
            })}
        </div>
      </div>
    </Popup>
  );
}
